package com.nine.aop.result;

import lombok.Data;

@Data
public class R<T> {

    private Integer code;
    private String msg;
    private T data;

    // 私有构造函数
    private R() {
    }

    /**
     * 成功
     */
    public static final int SUCCESS = 200;

    /**
     * 失败
     */
    public static final int FAIL = 500;

    public static <T> R<T> ok() {
        return buildResult(SUCCESS, "操作成功", null);
    }

    public static <T> R<T> ok(T data) {
        return buildResult(SUCCESS, "操作成功", data);
    }

    public static <T> R<T> ok(String msg) {
        return buildResult(SUCCESS, msg, null);
    }

    public static <T> R<T> ok(String msg, T data) {
        return buildResult(SUCCESS, msg, data);
    }

    public static <T> R<T> fail() {
        return buildResult(FAIL, "操作失败", null);
    }

    public static <T> R<T> fail(T data) {
        return buildResult(FAIL, "操作失败", data);
    }

    public static <T> R<T> fail(String msg) {
        return buildResult(FAIL, msg, null);
    }

    public static <T> R<T> fail(String msg, T data) {
        return buildResult(FAIL, msg, data);
    }

    // 判断返回是否成功
    public static <T> Boolean isSuccess(R<T> ret) {
        return R.SUCCESS == ret.getCode();
    }

    // 构建数据
    private static <T> R<T> buildResult(int code, String msg, T data) {
        R<T> r = new R<>();
        r.setCode(code);
        r.setMsg(msg);
        r.setData(data);
        return r;
    }

}
